//===----------------------------------------------------------------------===//
//
//                         BusTub
//
// clock_replacer.cpp
//
// Identification: src/buffer/clock_replacer.cpp
//
// Copyright (c) 2015-2019, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "buffer/clock_replacer.h"

namespace bustub {

ClockReplacer::ClockReplacer(size_t num_pages):num_pages(num_pages),currentClock(-1) {
    is_in_clock = std::vector<bool>(num_pages, 0);
    bit_ref = std::vector<bool>(num_pages, 0);
}

ClockReplacer::~ClockReplacer() = default;

bool ClockReplacer::Victim(frame_id_t *frame_id) {
    while (Size()) 
    {
        forward();
        if (!is_in_clock[currentClock])
        {
            continue;
        }
        if (bit_ref[currentClock])
        {
            bit_ref[currentClock] = false;
            continue; 
        }
        

        is_in_clock[currentClock] = false;
        bit_ref[currentClock] = false;
        *frame_id = currentClock;
        return true;
        
        
    }
    return false;
    
}

void ClockReplacer::Unpin(frame_id_t frame_id) {
    is_in_clock[frame_id] = true;
    bit_ref[frame_id] = true;
}

void ClockReplacer::Pin(frame_id_t frame_id) {
    is_in_clock[frame_id] = false;
    bit_ref[frame_id] = false;
}

size_t ClockReplacer::Size() {
    size_t num_in_clock = 0;
    for (size_t i = 0; i < num_pages; i++)
    {
        if (is_in_clock[i])
        {
            num_in_clock++;
        }
        
    }
    return num_in_clock;
    
}

void ClockReplacer::forward() {
    currentClock = (currentClock + 1) % num_pages;
}

}  // namespace bustub
